/**
 * 190128：更新redoList的清空，使操作中断redoList的添加并清空，以免不连贯的redo操作引起的bug
 * 20220304:[require] to [import]...jordia
 */

import {EventDispatcher} from 'three';

let listLength=20;
let redoList=[];
let undoList=[];
let redoEvent={type:'canRedo',paras:{value:false}};
let undoEvent={type:'canUndo',paras:{value:false}};
let eventCenter=new EventDispatcher();

export default class CommandManager{
    constructor(){}
    static set maxCount(num){
        listLength=num;
    }
    static get EventCenter(){
        return eventCenter;
    }
    static fireUndoEvent(bool){
        undoEvent.paras.value=bool;
        eventCenter.dispatchEvent(undoEvent);
    }
    static fireRedoEvent(bool){
        redoEvent.paras.value=bool;
        eventCenter.dispatchEvent(redoEvent);
    }
    static addUndo(cmd,isRedo){
        let index=undoList.findIndex((i)=>i===cmd);
        if(index!==-1)return;
        if(undoList.length<listLength){
            undoList.push(cmd);
        }else{
            undoList[0].destroy;
            undoList.copyWithin(0,1);
            undoList[listLength-1]=cmd;
        }
        if(!isRedo)CommandManager.clearRedoList();
        CommandManager.fireUndoEvent(undoList.length!==0);
        CommandManager.fireRedoEvent(redoList.length!==0);
    }
    static clearUndoList(){
        undoList=[];
        CommandManager.fireUndoEvent(undoList.length!==0);
    }
    static clearRedoList(){
        redoList=[];
        CommandManager.fireRedoEvent(redoList.length!==0);
    }
    static addRedo(cmd){
        let index=redoList.findIndex((i)=>i===cmd);
        if(index!==-1)return;
        if(redoList.length<listLength){
            redoList.push(cmd);
        }else{
            redoList[0].destroy;
            redoList.copyWithin(0,1);
            redoList[listLength-1]=cmd;
        }
        CommandManager.fireUndoEvent(undoList.length!==0);
        CommandManager.fireRedoEvent(redoList.length!==0);
    }
    static redo(){
        if(redoList.length===0){
            return;
        }
        redoList[redoList.length-1].execute(true);
        redoList.splice(redoList.length-1,1);
        CommandManager.fireUndoEvent(undoList.length!==0);
        CommandManager.fireRedoEvent(redoList.length!==0);
    }
    static undo(){
        if(undoList.length===0){
            return;
        }
        undoList[undoList.length-1].undo();
        undoList.splice(undoList.length-1,1);
        CommandManager.fireUndoEvent(undoList.length!==0);
        CommandManager.fireRedoEvent(redoList.length!==0);
    }
}